package websocket

import (
	"encoding/json"
	"github.com/kataras/iris/websocket"
	"github.com/ngaut/log"
	"server/bitkop/app/constants"
)

// 发送错误消息
func Error(connection websocket.Connection, pair string, code constants.WSCode, msg string) {

	errMsg := msg
	if msg == "" {
		errMsg = code.GetMessage()
	}

	result, err := json.Marshal(map[string]interface{}{
		"msg_id": constants.MSGID_ERROR_RESPONSE.Enum(),
		"code":   code.GetCode(),
		"pair":   pair,
		"msg":    errMsg,
	})

	if err != nil {
		log.Errorf("json encode data error, msg: %s", err.Error())
		return
	}

	connection.EmitMessage(result)
}

// 成功
func Success(connection websocket.Connection, pair string, msgId constants.MsgId, data interface{}) {
	result, err := json.Marshal(map[string]interface{}{
		"msg_id": msgId.Enum(),
		"code":   constants.WS_OK.GetCode(),
		"msg":    constants.WS_OK.GetMessage(),
		"pair":   pair,
		"data":   data,
	})

	if err != nil {
		log.Errorf("json marshal error, msg: %s", err.Error())
	}

	if connection == nil {
		return
	}

	connection.EmitMessage(result)
}
